function [tsData,IT] = tsDataFileIn(ts)
%tsDataFileIn - management of a tsData input file
%
%   [tsDataOut,IT] = tsDataFileIn(tsDataIn)
%
% This function checks if the input variable tsDataIn is a tsData object.
% If this test is passed, tsDataOut = tsDataIn and IT is true. 
% If the test is not passed and tsDataIn is a char variable, the function 
% checks if it exists a MATLAB .mat file with this name and carrying a 
% tsData object (see below for more details about this file).
% If tsDatain is undefined or empty, the MATLAB .mat file carrying a tsData 
% object can be managed in an interactive way. 
% If the tsData object should be extracted by a file:
% - if a single variable is carried by the file, it must necessarily be a
%   tsData object;
% - if two or more variables are carried bt the file, one and only one of 
%   them must be a tsData object. 
% If the file loading is successful, the extracted tsData object is 
% tsDataOut and IT is true. If no a valid tsData object is extracted, 
% tsDataOut is empty, IT is false and a warning message is shown.
 
% G. Teza, 2021   

if (nargin == 1) && ~isempty(ts)
    if isa(ts,'tsData')
        tsData = ts;
        IT = true;
        return
    elseif ischar(ts)
        filenat = ts;
    else
        ts = [];
    end
end
    
if nargin < 1 || isempty(ts) 
    [filena, pathna] = uigetfile(...
        {'*.mat','MAT-files (*.mat)'},...
        'INPUT TSDATA FILE');
    if ~isequal(filena,0) && ~isequal(pathna,0)
        filenat = fullfile(pathna,filena);
    end
end

if exist(filenat,'file')
    IT = true;
else
    IT = false;
end
if ~IT
    tsData = [];
    warning('Invalid input file - no output data');
    return
end

varfilet = load(filenat);
fnames = fieldnames(varfilet);
nf = numel(fnames);
if nf == 1
    fname1 = fnames{:};
    tsData = varfilet.(fname1);
    if isa(tsData,'tsData')
        IT = true;
    else
        IT = false;
    end
else
    Iok = false(nf,1);
    for k = 1:nf
        varext = varfile.(fnames{k});
        if isa(varext,'tsData')
            Iok(k) = true;
        end
    end
    if sum(Iok) == 1
        kok = Iok;
        tsData = varfile.(fnames{kok});
        IT = true;
    else
        IT = false;
    end
end
if ~IT
    warning('Invalid input file - no output data');
    tsData = [];
end    